package com.star.system.service.impl;

import com.star.common.exception.BizException;
import com.star.security.authentication.wxapp.WxappAuthenticationApi;
import com.star.security.authentication.wxapp.response.WxappResponse;
import com.star.system.service.WxappApi;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序api 非认证的写在这
 *
 * @author yangzj
 */
@Service
public class WxappApiImpl implements WxappApi {
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private WxappAuthenticationApi wxappAuthenticationApi;

    @Override
    public String getPhone(String code, Integer type) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("code", code);
        String accessToken = wxappAuthenticationApi.getAccessToken(type);
        Phone phone = restTemplate.postForObject(Uri.GET_PHONE, params, Phone.class, accessToken);
        if (phone == null || phone.getPhoneInfo() == null) {
            throw new BizException("微信小程序获取手机号失败");
        }
        return phone.getPhoneInfo().getPhoneNumber();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    static class Phone extends WxappResponse {
        @JsonAlias("phone_info")
        private PhoneInfo phoneInfo;
    }

    @Data
    static class PhoneInfo {
        private String phoneNumber;
    }


    interface Uri {
        /**
         * 获取电话 POST
         */
        String GET_PHONE = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}";
    }
}
